package com.dailyblue.java.spring.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dailyblue.java.spring.security.bean.Users;
import com.dailyblue.java.spring.security.mapper.UsersMapper;
import com.dailyblue.java.spring.security.service.UsersService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("userName",username);
        Users user = usersMapper.selectOne(wrapper);
        if(user==null){
            System.out.println("账号或者密码错误");
            throw new RuntimeException("账号或者密码错误");
        }
        System.out.println(user);
        System.out.println(new BCryptPasswordEncoder().encode(user.getPassword()));
        List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("manager1");
        return new User(username,new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}
